package com.itic.appbase.framework.utils;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayOpenPublicAccountCreateRequest;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayOpenPublicAccountCreateResponse;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.itic.appbase.framework.alipay.company.src.com.alipay.util.AlipayCore;
import com.itic.appbase.framework.alipay.company.src.com.alipay.util.AlipayNotify;
import com.itic.appbase.framework.alipay.company.src.com.alipay.util.AlipaySubmit;
import com.itic.appbase.framework.alipay.company.src.com.alipay.util.httpClient.HttpRequest;
import com.itic.appbase.framework.alipay.company.src.com.alipay.util.httpClient.HttpResultType;
import com.itic.mall.mobile.pay.CompanyPaySuccessVo;
import com.itic.mall.mobile.pay.CompanyPayVo;
import com.itic.mall.mobile.pay.PaySuccessVo;
import com.itic.mall.system.project.alipay.persistence.model.Alipay;
import com.itic.mall.system.project.alipaycompany.persistence.model.AlipayCompany;
import com.itic.mall.system.project.wxpay.persistence.model.Wxpay;

import net.sf.json.JSONObject;  
  
public class AliPayUtil {
	

	public static PaySuccessVo success( HttpServletRequest request, Alipay alipayConfig ) throws Exception { 
		/*String orderNum = "201801051003961540";
		String payTime = "2018-01-01 12:00:00";
		String payNo  = "123456";*/
		String orderNum = "";
		String payTime = "";
		String payNo  = "";
		PaySuccessVo paySuccessVo = new PaySuccessVo();
		Map<String, String> paramMap = getParamMap(request);
		//boolean signVerified = AlipaySignature.rsaCheckV2(paramMap,alipayConfig.getAlipayPublicKeyDevelop(), "UTF-8","RSA2");
		boolean signVerified = true;//上线之前注释掉//AlipaySignature.rsaCheckV1(paramMap,alipayConfig.getAlipayPublicKey(), "UTF-8","RSA2");
		//if( signVerified && ("TRADE_SUCCESS".equals(paramMap.get("trade_status")) || "TRADE_FINISHED".equals(paramMap.get("trade_status"))) ){
				//获得ORDER——ID
			    orderNum = getCleanParams(request, "out_trade_no");
			    payTime = getCleanParams(request, "gmt_payment");
			    payNo = getCleanParams(request, "trade_no");
			    paySuccessVo.setOrderNo(orderNum);
			    paySuccessVo.setPayNo(payNo);
			    paySuccessVo.setPayTime(payTime);
		//}
		return paySuccessVo;
	}
	/**
	 * 批量支付成功回调
	 * @param request
	 * @param alipayCompanyConfig
	 * @return
	 * @throws Exception
	 */
	public static CompanyPaySuccessVo successCompany(HttpServletRequest request,AlipayCompany alipayCompanyConfig)throws Exception{
		CompanyPaySuccessVo companyPaySuccessVo = new CompanyPaySuccessVo();
		
		//获取支付宝POST过来反馈信息
		Map<String,String> params = new HashMap<String,String>();
		Map requestParams = request.getParameterMap();
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";
			}
			//乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
			//valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
			params.put(name, valueStr);
		}
		
		//获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
		//批量付款数据中转账成功的详细信息

		String success_details = new String(request.getParameter("success_details").getBytes("ISO-8859-1"),"UTF-8");

		//批量付款数据中转账失败的详细信息
		String fail_details = new String(request.getParameter("fail_details").getBytes("ISO-8859-1"),"UTF-8");

		//获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//

		if(AlipayNotify.verify(params)){//验证成功
			//////////////////////////////////////////////////////////////////////////////////////////
			//请在这里加上商户的业务逻辑程序代码

			//——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
			
			//判断是否在商户网站中已经做过了这次通知返回的处理
				//如果没有做过处理，那么执行商户的业务程序
				//如果有做过处理，那么不执行商户的业务程序
				
			System.out.println("success");	//请不要修改或删除

			//——请根据您的业务逻辑来编写程序（以上代码仅作参考）——
			String notify_id = getCleanParams(request, "notify_id");
			String batch_no = getCleanParams(request, "batch_no");
			String sign =  getCleanParams(request, "sign");
			companyPaySuccessVo.setBatch_no(batch_no);
		    companyPaySuccessVo.setFail_details(fail_details);
		    companyPaySuccessVo.setNotify_id(notify_id);
		    companyPaySuccessVo.setSign(sign);
		    companyPaySuccessVo.setSuccess_details(success_details);

			//////////////////////////////////////////////////////////////////////////////////////////
		}else{//验证失败
			System.out.println("fail");
		}
		
		return companyPaySuccessVo;
	}
	/**
	 * 批量支付
	 * @param request
	 * @param alipayCompanyConfig
	 * @param companyPayVo
	 * @return
	 * @throws Exception
	 */
	public static String companyPay(HttpServletRequest request,AlipayCompany alipayCompanyConfig, CompanyPayVo companyPayVo)throws Exception{
		
		String result = "";
		String service = alipayCompanyConfig.getService();
		String partner = alipayCompanyConfig.getPartner();
		String _input_charset = alipayCompanyConfig.getInputCharset();
		String sign_type = alipayCompanyConfig.getSignType();
		String sign = "";
		String notify_url = alipayCompanyConfig.getNotifyUrl();
		String account_name = alipayCompanyConfig.getAccountName();
		String email = alipayCompanyConfig.getAccount();
		String detail_data = companyPayVo.getDetail_data();
		String batch_no = companyPayVo.getBatch_no();
		String batch_num = companyPayVo.getBatch_num();
		String batch_fee = companyPayVo.getBatch_fee();
		String pay_date = companyPayVo.getPay_date();
	     Map<String, String> m = new HashMap<String, String>();
	     m.put("service", service);
	     m.put("partner", partner);
	     m.put("_input_charset", _input_charset);
	     m.put("notify_url", notify_url);
	     m.put("account_name", account_name);
	     m.put("email", email);
	     m.put("detail_data", detail_data);
	     m.put("batch_no", batch_no);
	     m.put("batch_num", batch_num);
	     m.put("batch_fee", batch_fee);
	     m.put("pay_date", pay_date);
	     Map<String, String> resultMap = AlipayCore.paraFilter(m);//去掉空值与签名参数后的新签名参数组
	     //建立请求，以表单HTML形式构造（默认）
	     String strParaFileName = "alipay.csv";
	     String strFilePath = "C:\\Users\\Administrator\\Desktop\\alipay.csv";
	     //建立请求，以模拟远程HTTP的POST请求方式构造并获取支付宝的处理结果,如果接口中没有上传文件参数，那么strParaFileName与strFilePath设置为空值
	     result =  AlipaySubmit.buildRequest(m, "get", "submit");
	     HttpRequest requeststr = new HttpRequest(HttpResultType.BYTES);
		// 设置编码集
	   // String strResult =  AlipaySubmit.buildRequest("alipay", strFilePath,m); 
		// result = AlipaySubmit.buildRequest(strParaFileName,strFilePath,m);
		return result;
	}

	/**
	 * ali支付工具类
	 * 
	 * @param request
	 * @param weixinpayConfig
	 * @param vo
	 * @return
	 */
	public static String pay(HttpServletRequest request,Alipay alipayConfig, PayVo vo) throws Exception { 
		
		String result = "";
		
		String total_amout = vo.getTotalMoney();
		
		//如果是测试环境，则使用0.01元
		String isTest = alipayConfig.getIsTest();
		if( StringHelper.isNoneBlank(isTest) && "open".equals(isTest) ){
			total_amout = "0.01";
		}
		
		String body = vo.getDesc();
		String subject = alipayConfig.getSubject();
		String out_trade_no = vo.getOrderNum();
         
	     Map<String, String> m = new HashMap<String, String>();

         m.put("body", body);
         m.put("subject", subject);
         m.put("out_trade_no", out_trade_no);
         m.put("timeout_express", "30m");         
         m.put("total_amount", total_amout);
         m.put("seller_id", alipayConfig.getPartner());
         m.put("product_code", "QUICK_MSECURITY_PAY");

         JSONObject bizcontentJson= JSONObject.fromObject(m);

        
          
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",alipayConfig.getAppId(),alipayConfig.getAppPrivateKey(),"json","UTF-8",alipayConfig.getAlipayPublicKey(),"RSA2");
        AlipayTradeAppPayRequest aliRequest = new AlipayTradeAppPayRequest();
        aliRequest.setBizContent(bizcontentJson.toString());
        
        String serviceString = alipayConfig.getNotifyUrl();
        aliRequest.setNotifyUrl( serviceString );
        AlipayTradeAppPayResponse aliResponse = alipayClient.sdkExecute(aliRequest);
       
        if( aliResponse.isSuccess() ){
        	result = aliResponse.getBody();
        }
        return result;
    }  
	
	public Boolean  request(String accessToken) throws AlipayApiException{
		Boolean result = false;
		AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do","app_id","your private_key","json","GBK","alipay_public_key","RSA2");
		AlipayOpenPublicAccountCreateRequest request = new AlipayOpenPublicAccountCreateRequest();
		request.setBizContent("{" +
		"\"bind_account_no\":\"test001\"," +
		"\"display_name\":\"test001\"," +
		"\"agreement_id\":\"29022222\"," +
		"\"real_name\":\"张三\"," +
		"\"from_user_id\":\"2088801234567890\"," +
		"\"remark\":\"备注信息\"" +
		"  }");
		AlipayOpenPublicAccountCreateResponse response = alipayClient.execute(request);
		if(response.isSuccess()){
		System.out.println("调用成功");
		} else {
		System.out.println("调用失败");
		}
		//响应示例
		return result;
	}
    /**
     * 支付宝退款
     * @param out_trade_no 
     * @param trade_no
     * @param refund_amonut
     * @param refund_reason
     * @return
     * @throws AlipayApiException
     */
	public static Map<String,Object> refund(String out_trade_no,String trade_no,double refund_amonut,String refund_reason) throws AlipayApiException{
		Map<String,Object> returnMap = new HashMap<String,Object>();
		
		AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do","app_id","your private_key","json","GBK","alipay_public_key","RSA2");
		AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
		
		 Map<String, String> m = new HashMap<String, String>();

         m.put("out_trade_no", out_trade_no);//商户订单号
         m.put("trade_no", trade_no);//支付宝交易号
         m.put("refund_amonut", String.valueOf(refund_amonut));//需要退款的金额，该金额不能大于订单金额,单位为元，支持两位小数
         m.put("refund_reason", refund_reason);//退款的原因说明
         JSONObject bizcontentJson= JSONObject.fromObject(m);
         request.setBizContent(bizcontentJson.toString());
        /*
		request.setBizContent("{" +
		"\"out_trade_no\":\"+out_trade_no+\"," +
		"\"trade_no\":\"2014112611001004680073956707\"," +
		"\"refund_amount\":200.12," +
		"\"refund_currency\":\"USD\"," +
		"\"refund_reason\":\"正常退款\"," +
		"\"out_request_no\":\"HZ01RF001\"," +
		"\"operator_id\":\"OP001\"," +
		"\"store_id\":\"NJ_S_001\"," +
		"\"terminal_id\":\"NJ_T_001\"," +
		"      \"goods_detail\":[{" +
		"        \"goods_id\":\"apple-01\"," +
		"\"alipay_goods_id\":\"20010001\"," +
		"\"goods_name\":\"ipad\"," +
		"\"quantity\":1," +
		"\"price\":2000," +
		"\"goods_category\":\"34543238\"," +
		"\"body\":\"特价手机\"," +
		"\"show_url\":\"http://www.alipay.com/xxx.jpg\"" +
		"        }]" +
		"  }");
		*/
		AlipayTradeRefundResponse response = alipayClient.execute(request);
		if(response.isSuccess()){
		System.out.println("调用成功");
		} else {
		System.out.println("调用失败");
		}
		//响应示例
		
		return returnMap;
	}
	public static void back(HttpServletRequest request,Wxpay weixinpayConfig, PayVo vo) { 
		
	}
	
	
	public static Map<String,String> getParamMap(HttpServletRequest request){
		Map<String,String> params = new HashMap<String,String>();
		Map<String,String[]> requestParams = request.getParameterMap();
		if( null != requestParams ){
			for( Iterator<String> iter = requestParams.keySet().iterator();iter.hasNext();){
				String name = (String)iter.next();
				String[] values = (String[]) requestParams.get(name);
				String valueStr = "";
				for( int i=0;i<values.length;i++){
					valueStr=(i==values.length-1)?valueStr+values[i]:valueStr+values[i]+",";
				}
				//乱码解决，这段代码再出现乱码时使用。如果masign和sign不相等也可以使用这段代码
				//valueStr=new String(valueStr.getBytes("ISO-8859-1"),"gbk");
				params.put(name,valueStr);
				
			}
		}
		return params;
	}
	
	 /**
     * 获取request中的指定参数，并进行trim处理.
     * 
     * @param request
     * @param paramName
     * @return
     * @throws
     */
    public static String getCleanParams(HttpServletRequest request, String paramName) {
        String result = null;
        String param = request.getParameter(paramName);
        result = StringHelper.getCleanString(param);
        return result;
    }
}
